package org.drl.tvkit.task;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.nostra13.universalimageloader.utils.L;

/**
 * 第二个主线程
 * 
 * @author hljdrl@gmail.com
 */
public final class TwoTask extends Thread {
	private String TAG = "VooleTask";
	private volatile boolean mQuit = false;
	private final BlockingQueue<TaskSub> mQueue;

	public TwoTask() {
		mQueue = new LinkedBlockingQueue<TaskSub>();

	}

	public void quit() {
		try {
			mQuit = true;
			interrupt();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		L.d(TAG, "quit");
	}

	public void addTaskSub(final TaskSub _taskSub) {
		mQueue.add(_taskSub);
		L.d(TAG, "addTaskSub");
	}

	@Override
	synchronized public void run() {
		L.d(TAG, "running.....");
		android.os.Process
				.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
		TaskSub request;
		while (true) {
			try {
				request = mQueue.take();
			} catch (InterruptedException e) {
				if (mQuit) {
					return;
				}
				continue;
			}
			if(request!=null){
				try{
					request.runTaskSub();
				}catch(Exception ex){
					ex.printStackTrace();
				}catch(Error error){
					error.printStackTrace();
				}
			}
			System.gc();
		}

	}
}
